package cn.lfzj.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import cn.lfzj.model.User;

public class UserDao {
	private Connection conn;

	private void getConnection() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://localhost:3306/test?characterEncoding=utf8";
			conn = DriverManager.getConnection(url, "root", "jisuanjixi");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void close() {
		try {
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public int insert(User user) {
		int result = 0;
		this.getConnection();
		try {
			String sql = "insert into users(username,password,name) values(?,?,?)";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, user.getUsername());
			ps.setString(2, user.getPassword());
			ps.setString(3, user.getName());
			result = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.close();
		return result;
	}

	public User select(String username, String password) {
		this.getConnection();
		User user = null;
		try {
			String sql = "select * from users where username = ? and password = ?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, username);
			ps.setString(2, password);
			ResultSet rs = ps.executeQuery();
			if (rs.next()) {
				user = new User();
				user.setUsername(rs.getString("username"));
				user.setName(rs.getString("name"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.close();
		return user;
	}

	public void updatePwd(String username, String password) {
		this.getConnection();
		try {
			String sql = "update users set password=? where username=?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, password);
			ps.setString(2, username);
			ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.close();
	}
}
